<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2022-12-05 17:19:12
 * @Last Modified time: 2022-12-05 19:31:30
 */

namespace addon\alioss\services;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use OSS\Core\OssException;
use OSS\OssClient;
use frank\exception\CommonException;

/**
 * 阿里云OSS存储支持
 * Class AliossService
 * @package addon\alioss\services
 */
class AliossService 
{
    /**
     * 设置阿里云OSS参数配置
     * @param unknown $filePath 上传图片路径
     * @param unknown $key 上传到阿里云后保存的文件名
     */
    public function putFile($param)
    {
        $file_path = $param[ "file_path" ];
        $key = $param[ "key" ];
        if (sysconf('oss_type') == 'alioss') {
            $accessKey = sysconf('alioss_access_key');
            $accesssecret = sysconf('alioss_secret_key');
            $bucket = sysconf('alioss_bucket');
            // 节点
            $endpoint = sysconf('alioss_region');
	        if(empty($accessKey)){
	        	throw new CommonException('阿里云OSS[访问密钥]未配置');
	        }
	        if(empty($accesssecret)){
	        	throw new CommonException('阿里云OSS[安全密钥]未配置');
	        }
	        if(empty($bucket)){
	        	throw new CommonException('阿里云OSS[空间名称]未配置');
	        }
	        if(empty($endpoint)){
	        	throw new CommonException('阿里云OSS[节点]未配置');
	        }
            try {
                $ossClient = new OssClient($accessKey, $accesssecret, $endpoint);
                $result = $ossClient->uploadFile($bucket, $key, $file_path);
                $path = $result[ "info" ][ "url" ];
                //返回图片的完整URL
                $data = [
                	"oss_type" => sysconf('oss_type'),
                    "path" => $file_path,
                    "url" => $path,
                    "domain" => sysconf('alioss_http').'://'.$result['oss-requestheaders']['Host'] ?? $endpoint,
                    "bucket" => $bucket
                ];
                return $data;
            } catch (OssException $e) {
				throw new CommonException($e->getMessage());
            }
        }
    }
}